package com.today.usercenter.ui.activities;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.today.lib.common.Global;
import com.today.lib.common.network.entity.EmptyResponseEntity;
import com.today.lib.common.ui.base.RxBaseActivity;
import com.today.lib.common.utils.ToastUtils;
import com.today.usercenter.R;
import com.today.usercenter.R2;
import com.today.usercenter.bus.events.LoginEvent;
import com.today.usercenter.listener.OnUserLoginListener;
import com.today.usercenter.network.RetrofitHelper;
import com.today.usercenter.network.entity.request.PhoneLoginRequestEntity;
import com.today.usercenter.utils.InputUtils;
import com.today.usercenter.utils.LoginUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by User on 2017/2/28.
 */

public class RegisterActivity extends RxBaseActivity implements View.OnClickListener {
    private Context mContext;
    private Activity mActivity;
    @BindView(R2.id.code)
    EditText mCode;
    @BindView(R2.id.getcode)
    TextView mGetCode;
    @BindView(R2.id.mobile)
    EditText mMobile;
    @BindView(R2.id.password)
    EditText mPassword;
    @BindView(R2.id.finish)
    TextView mFinish;
    @BindView(R2.id.toolbar)
    Toolbar mToolbar;

    private DisplayMetrics mDisplayMetrics;
    private float density;
    private int mType;

    public static final int TYPE_REGISTER = 0;
    public static final int TYPE_RESET_PWD = 1;
    public static final int TYPE_BIND_PHONE = 2;

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        mContext = this;
        mActivity = this;
        mDisplayMetrics = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        density = mDisplayMetrics.density;
        initView();

        initToolbar();

        EventBus.getDefault().register(this);
    }

    private void initToolbar() {
        mType = getIntent().getIntExtra("type", TYPE_REGISTER);
        switch (mType) {
            case TYPE_RESET_PWD:
                mToolbar.setTitle(R.string.reset_pwd);
                break;
            case TYPE_BIND_PHONE:
                mToolbar.setTitle(R.string.bind_mobile);
                break;
            default:
                mToolbar.setTitle(R.string.quick_register);
                break;
        }

        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        mToolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void gotLoginMessage(LoginEvent loginEvent) {
        if (loginEvent.status == LoginEvent.STATUS_LOGIN)
            finish();
    }

    private void initView() {


        mFinish.setOnClickListener(this);
        mGetCode.setOnClickListener(this);
        mMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (InputUtils.isLegalCellphone(s.toString())) {
                    mGetCode.setClickable(true);
                    mGetCode.setBackgroundResource(R.drawable.round_btn_bg);
                } else {
                    mGetCode.setClickable(false);
                    mGetCode.setBackgroundResource(R.drawable.round_btn_bg_gray);
                }

                if (InputUtils.isLegalCellphone(mMobile.getText().toString())
                        && !TextUtils.isEmpty(mCode.getText().toString())
                        && InputUtils.isLegalPwd(mPassword.getText().toString())) {
                    mFinish.setClickable(true);
                    mFinish.setBackgroundResource(R.drawable.round_btn_bg);
                } else {
                    mFinish.setClickable(false);
                    mFinish.setBackgroundResource(R.drawable.round_btn_bg_gray);
                }
            }
        });
        mCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (InputUtils.isLegalCellphone(mMobile.getText().toString())
                        && !TextUtils.isEmpty(mCode.getText().toString())
                        && InputUtils.isLegalPwd(mPassword.getText().toString())) {
                    mFinish.setClickable(true);
                    mFinish.setBackgroundResource(R.drawable.round_btn_bg);
                } else {
                    mFinish.setClickable(false);
                    mFinish.setBackgroundResource(R.drawable.round_btn_bg_gray);
                }
            }
        });
        mPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (InputUtils.isLegalCellphone(mMobile.getText().toString())
                        && !TextUtils.isEmpty(mCode.getText().toString())
                        && InputUtils.isLegalPwd(mPassword.getText().toString())) {
                    mFinish.setClickable(true);
                    mFinish.setBackgroundResource(R.drawable.round_btn_bg);
                } else {
                    mFinish.setClickable(false);
                    mFinish.setBackgroundResource(R.drawable.round_btn_bg_gray);
                }
            }
        });
        // 设置密码是否显示
        mPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Drawable drawable = mPassword.getCompoundDrawables()[2];
                if (drawable == null) {
                    return;
                }
                if (mPassword.getInputType() == InputType.TYPE_CLASS_TEXT) {
                    drawable = getResources().getDrawable(R.drawable.pwd_gone);
                    drawable.setBounds(0, 0, (int) (24 * density), (int) (13 * density));
                    mPassword.setCompoundDrawables(null, null, drawable, null);
                    mPassword.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    mPassword.setSelection(mPassword.getText().length());
                } else if (mPassword.getInputType() == (InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {
                    drawable = getResources().getDrawable(R.drawable.pwd_visible);
                    drawable.setBounds(0, 0, (int) (24 * density), (int) (13 * density));
                    mPassword.setCompoundDrawables(null, null, drawable, null);
                    mPassword.setInputType(InputType.TYPE_CLASS_TEXT);
                    mPassword.setSelection(mPassword.getText().length());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.getcode) {
            mGetCode.setClickable(false);
            mMobile.setEnabled(false);
            getMobileCode(mMobile.getText().toString());
            TimeCount time = new TimeCount(60000, 1000);
            time.start();

        } else if (i == R.id.finish) {
            String phoneNum = mMobile.getText().toString();
            String pwd = mPassword.getText().toString();
            String code = mCode.getText().toString();
            if (!InputUtils.isLegalCellphone(phoneNum)) {
                ToastUtils.showToast(getString(R.string.mobile_error));
            } else if (!InputUtils.isLegalPwd(pwd)) {
                ToastUtils.showToast(getString(R.string.please_input_legal_mobile));
            } else {
                mFinish.setClickable(false);

                switch (mType) {
                    case TYPE_RESET_PWD:
                        register(phoneNum, InputUtils.encodeUserPwd(pwd), code);
                        break;
                    case TYPE_BIND_PHONE:
                        bindMobile();
                        break;
                    default:
                        register(phoneNum, InputUtils.encodeUserPwd(pwd), code);
                        break;
                }
            }

        }
    }

    /**
     * 注册手机号
     *
     * @author jqt
     * create at 2017/4/1 10:41
     */
    private void register(String phoneNum, String pwd, String code) {
        LoginUtils loginUtils = (LoginUtils) Global.loginHelper;


        loginUtils.setOnUserLoginListener(new OnUserLoginListener() {
            @Override
            public void onSuccess() {
                if (mType == TYPE_RESET_PWD)
                    ToastUtils.showToast("密码重置成功");
                else if (mType == TYPE_REGISTER)
                    ToastUtils.showToast("注册成功");
                mFinish.setClickable(true);
            }

            @Override
            public void onFailed() {
                mFinish.setClickable(true);
                mMobile.setEnabled(true);
            }
        });
        loginUtils.login(new PhoneLoginRequestEntity(phoneNum, pwd, code));
    }

    /**
     * 绑定手机号
     *
     * @author jqt
     * create at 2017/4/1 10:40
     */
    private void bindMobile() {
    }

    /**
     * 获取验证码
     *
     * @author jqt
     * create at 2017/4/1 10:40
     */
    private void getMobileCode(String phoneNum) {
        RetrofitHelper.getUserApi().getCode(phoneNum).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(emptyResponseEntity -> {
                    if (emptyResponseEntity.busCode == EmptyResponseEntity.STATUS_OK) {
                        ToastUtils.showToast(getString(R.string.send_code_success));
                    } else {
                        ToastUtils.showToast(emptyResponseEntity.busMsg);
                    }
                }, throwable -> {
                    ToastUtils.showToast(getString(R.string.send_code_fail));
                    throwable.printStackTrace();
                });
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            if (mGetCode != null) {
                mGetCode.setText(getString(R.string.get_code));
                mGetCode.setClickable(true);
                mGetCode.setBackgroundResource(R.drawable.round_btn_bg);

                mMobile.setEnabled(true);
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (mGetCode != null) {
                mGetCode.setBackgroundResource(R.drawable.round_btn_bg_gray);
                mGetCode.setText(getString(R.string.resend) + "(" + millisUntilFinished / 1000 + "s)");
            }
        }
    }
}
